<?php

namespace backend\models\service;

use Yii;
use yii\data\Sort;
use yii\data\ActiveDataProvider;
use backend\models\odm\TweetOdm as Tweet;

class TweetService extends Tweet {

    private $_query;
    public $key_words;

    /**
     * @inheritdoc
     */
    public function rules() {
        return array_merge(parent::rules(), [
            [['key_words'], 'string'],
//            [['chapter_id','op_id'], 'required'],
        ]);
    }
    
    public function init() {
        parent::init();
        $this->_query = static::find();
    }

   

    /**
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function getQuerySearch($params) {
        $this->load($params);
        $this->_query->andFilterWhere([
            'id' => $this->id,
            'op_id' => $this->op_id,
            'channel_id' => $this->channel_id,
            'status' => $this->status,
            'platform' => $this->platform
        ]);
        $this->_query->andFilterWhere(['like', 'novel_name', $this->novel_name]);
        $this->time($this->_query, [
            'create_time',
        ]);
        return $this;
    }

    public function getList() {
        $query = $this
            ->getQuerySearch(Yii::$app->request->queryParams)
            ->getQuery();
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        
        $dataProvider->setSort(['defaultOrder' => ['create_time' => SORT_DESC]]);
        return $dataProvider;
    }

    /**
     *
     * 时间的搜索
     *
     * @param $query , array $colmns
     *
     * @return $query
     * */
    private function time(&$query, $colmns) {
        foreach ($colmns as $key => $value) {
            if ($this->$value != '') {
                $query->andWhere(['between', $value, strtotime($this->$value), strtotime($this->$value) + 86400]);
            } else {
                $this->$value = null;
            }
        }
        return $query;
    }

    public function getQuery() {
        return $this->_query;
    }
    
    public static function uniqidSn() {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $uuid = substr($charid, 0, 8).substr($charid, 8, 4).substr($charid,12, 4).substr($charid,16, 4).substr($charid,20,12);
        return $uuid;
    }
    
    /**
     * 推文数量
     */
    public function getTweetNums($cid){
        $sql = 'select count(*) as n from xs_tweet where channel_id = ' . $cid ;
        $res = Yii::$app->db->createCommand($sql)->queryOne();

        return $res['n'];
    }
        

}
